package com.wephone.Student.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.wephone.Student.R;
import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.ZhidaoAskListResponse;
import com.wephone.Student.bean.data.ZhidaoAskData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.PullToRefreshView;
import com.wephone.Student.util.PullToRefreshView.OnFooterRefreshListener;
import com.wephone.Student.util.PullToRefreshView.OnHeaderRefreshListener;
import com.wephone.Student.util.RoundImageView;

public class ZhidaoMyTieziListActivity extends BaseActivity {
	private PullToRefreshView pullToRefreshListView;
	private ListView listView;
	private ListViewAdapter adapter;
	private List<ZhidaoAskData> results = new ArrayList<ZhidaoAskData>();
	private int listItemIdx;
	private String uid;
	
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoMyTieziListActivity.this,ZhidaoAskListResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					ZhidaoAskListResponse res = (ZhidaoAskListResponse)response;
					
					if(adapter.pageIdx>=res.getTotalPage() || res.getData().size()<Constants.PAGE_SIZE){
						adapter.hasMore = false;
					}else{
						adapter.pageIdx++;
					}
					results.addAll(res.getData());
					adapter.notifyDataSetChanged();
				}
			}
		};
		return handler;
	}
	
	private MyResponseHandler getHandler2(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoMyTieziListActivity.this,BaseResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					results.clear();
					adapter.hasMore = true;
					adapter.pageIdx = 1;
					
					RequestParams params = new RequestParams();
					params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("Page", "1");
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_MY_ASK_LIST_URL, params, getHandler());
					
					Toast.makeText(getApplicationContext(), "帖子删除成功", Toast.LENGTH_SHORT).show();
				}
			}
		};
		return handler;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1 && resultCode==11){
			results.clear();
			adapter.hasMore = true;
			adapter.pageIdx = 1;
			
			RequestParams params = new RequestParams();
			params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
			params.put("Page", "1");
			params.put("PageSize", ""+Constants.PAGE_SIZE);
			HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_MY_ASK_LIST_URL, params, getHandler());
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zhi_dao_my_tiezi_list);
		
		init();
	}
	
	private void init(){
		listView = (ListView)findViewById(R.id.listview);
		adapter = new ListViewAdapter();
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new ListView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bundle bundle = new Bundle();
				bundle.putSerializable("askData", results.get(arg2));
				startActivity(new Intent(getApplicationContext(),ZhidaoAnswerListActivity.class).putExtras(bundle));
			}});
//		listView.setOnLongClickListener(new ListView.OnLongClickListener(){
//			@Override
//			public boolean onLongClick(View arg0) {
//				// TODO Auto-generated method stub
//				new AlertDialog.Builder(ZhidaoMyTieziListActivity.this).setTitle("提示")
//				.setItems(new String[]{"删除问题"}, new DialogInterface.OnClickListener(){
//					@Override
//					public void onClick(DialogInterface arg0, int arg1) {
//						if(arg1==0){
//							RequestParams params = new RequestParams();
//							params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
//							params.put("id", results.get(arg1).getId());
//							HttpClient.getInstance().get(Constants.API_ZHIDAO_DEL_ASK_URL, params, getHandler2());
//						}
//					}})
//				.setNegativeButton("取消", null).show();
//				return false;
//			}});
		
		pullToRefreshListView = (PullToRefreshView)findViewById(R.id.pull_refresh_listview);
		pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
			@Override
			public void onHeaderRefresh(PullToRefreshView view) {
				results.clear();
				adapter.hasMore = true;
				adapter.pageIdx = 1;
				
				RequestParams params = new RequestParams();
				params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
				params.put("Page", "1");
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_MY_ASK_LIST_URL, params, getHandler());
			}
		});
		pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
			@Override
			public void onFooterRefresh(PullToRefreshView view) {
				if(!adapter.hasMore){
					pullToRefreshListView.onFooterRefreshComplete();
					return;
				}
				RequestParams params = new RequestParams();
				params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
				params.put("Page", ""+adapter.pageIdx);
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_MY_ASK_LIST_URL, params, getHandler());
			}
		});
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			uid = bundle.getString("uid");
			String username = bundle.getString("username");
			if(!TextUtils.isEmpty(uid)){
				if(!uid.equals(BaseActivity.getMyInfo(getApplicationContext()).getuId())){
					((TextView)findViewById(R.id.top_title_text)).setText(username+"的帖子");
				}
				
				RequestParams params = new RequestParams();
				params.put("uid", uid);
				params.put("Page", "1");
				params.put("PageSize", ""+Constants.PAGE_SIZE);
				HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_MY_ASK_LIST_URL, params, getHandler());
			}
		}
	}
	
	private class ListViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		
		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.include_zhi_dao_my_tiezi_list_item, null);
			}
			ZhidaoAskData askData = results.get(position);
			TextView itemTitle = (TextView)convertView.findViewById(R.id.item_title_text);
			itemTitle.setText(askData.getTitle());
			TextView itemContent = (TextView)convertView.findViewById(R.id.item_content);
			itemContent.setText(askData.getContent());
			TextView itemNumText = (TextView)convertView.findViewById(R.id.item_num_text);
			itemNumText.setText(askData.getCommentCount());
			TextView zhidaoEditText = (TextView)convertView.findViewById(R.id.item_zhidao_edit_text);
			if(!uid.equals(BaseActivity.getMyInfo(getApplicationContext()).getuId())){
				zhidaoEditText.setVisibility(View.GONE);
			}else{
				zhidaoEditText.setTag(position);
				zhidaoEditText.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						listItemIdx = Integer.parseInt(arg0.getTag().toString());
						new AlertDialog.Builder(ZhidaoMyTieziListActivity.this)
						.setItems(new String[]{"编辑帖子","删除帖子","取消"}, new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								if(arg1==0){
									Bundle bundle = new Bundle();
									bundle.putSerializable("askData", results.get(listItemIdx));
									startActivityForResult(new Intent(getApplicationContext(),ZhidaoEditTieziActivity.class).putExtras(bundle),1);
								}else if(arg1==1){
//									System.out.println("---------listItemIdx--------"+results.get(listItemIdx).getId());
									RequestParams params = new RequestParams();
									params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
									params.put("id", results.get(listItemIdx).getId());
									HttpClient.getInstance().get(Constants.API_ZHIDAO_DEL_ASK_URL, params, getHandler2());
								}
							}})
						.show();
					}
				});
			}
			TextView questionAskName = (TextView)convertView.findViewById(R.id.question_ask_name);
			questionAskName.setText(askData.getuInfo().getuName());
			RoundImageView itemImage = (RoundImageView)convertView.findViewById(R.id.question_ask_image);
			if(!TextUtils.isEmpty(askData.getuInfo().getuIcon())){
				DisplayImageOptions options = new DisplayImageOptions.Builder()
		        .showStubImage(R.drawable.default_user_logo)
		        .showImageOnFail(R.drawable.default_user_logo)
		        .bitmapConfig(Bitmap.Config.ARGB_8888)
		        .cacheInMemory()
		        .cacheOnDisc()
//		        .displayer(new RoundedBitmapDisplayer(1000))
		        .build();
				String endStr = askData.getuInfo().getuIcon().substring(askData.getuInfo().getuIcon().lastIndexOf("."));
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+askData.getuInfo().getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
			}else{
				itemImage.setImageResource(R.drawable.default_user_logo);
			}
			return convertView;
		}		
	}

}
